const cookieParser = process.server ? require('cookieparser') : undefined

export const state = () => {
    return {
        // 登录用户的状态
        user: ''
    }
}


export const mutations = {
    setUser(state, data) {
        state.user = data
    }
}

export const actions = {
    // nuxtServerInit 特殊方法
    // 服务端渲染完成前调用
    nuxtServerInit({
        commit
    }, {
        req
    }) {
        let user = null
        if (req.headers.cookie) {
            // cookie 字符串转js对象
            const parsed = cookieParser.parse(req.headers.cookie)
            try {
                user = JSON.parse(parsed.user)
            } catch (err) {
                // No valid cookie found
            }
        }
        commit('setUser', user)
    }
}